package com.fbli.udp.homework;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/***
 * 发送端B
 */
public class Homework02SenderB {
    public static void main(String[] args) throws IOException {
        //1.创建一个DatagramSocket在9998端口接收和发送数据
        DatagramSocket datagramSocket = new DatagramSocket(9998);
        //将需要发送的数据,封装到DatagramPacket对象
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的问题");
        String send = scanner.next();
        byte[] data = send.getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.0.104"), 8888);
        //说明：封装的DatagramPacket对象 data内容字节数组，data.length,主机(端口),端口
        //发送
        datagramSocket.send(packet);
        //接收A回复的消息
        datagramSocket.receive(packet);
        //4.把packet进行拆包，取出数据，并显示。
        int length = packet.getLength();//实际接收到的数据长度
        data = packet.getData();//接收到数据
        String s = new String(data, 0, length);
        System.out.println(s);
        //关闭资源
        datagramSocket.close();
        System.out.println("B端退出");
    }
}
